<!--
 * @Description: 新增话术
 * @Author: lixianggang
 * @Date: 2022-10-17 14:25:24
 * @LastEditors: lixianggang
 * @LastEditTime: 2022-11-14 17:26:03
-->
<template>
  <div>
    <div class="header-btn">
      <div>新增话术</div>
      <div>
        <el-button type="primary" @click="submit">确认</el-button>
        <el-button type="info" plain @click="goBack">返回</el-button>
      </div>
    </div>
    <div class="from-wrap" v-loading="pageLoading">
      <el-form :model="groupForm" :rules="rules" ref="groupForm" label-width="100px">
        <el-form-item label="选择分组" prop="categoryId">
          <el-select v-model="groupForm.categoryId" placeholder="请选择分组">
            <el-option v-for="item in personGroupList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="标题" prop="materialName">
          <el-input v-model="groupForm.materialName" clearable maxlength="30" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="话术类型" prop="verbalType">
          <el-radio-group v-model="groupForm.verbalType" @change="handleChange">
            <el-radio :label="1">文本</el-radio>
            <el-radio :label="2">图文</el-radio>
            <!-- 视频 25 M -->
            <el-radio :label="3">视频</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="groupForm.verbalType == 1" label="话术内容" prop="content">
          <el-input v-model="groupForm.content" clearable type="textarea" :rows="4" maxlength="200"
            show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="图文" prop="imgUrl" v-if="groupForm.verbalType == 2">
          <el-upload action :limit="1" :show-file-list="false"
            :before-upload="val => beforeUpload(val, 'uploadInterface', 5)">
            <div>
              <img v-if="!appear" :src="groupForm.imgUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              <div slot="tip" class="el-upload__tip">
                只能上传 jpg/png/gif/svg 文件，且不超过5MB
              </div>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="视频" prop="imgUrl" v-if="groupForm.verbalType == 3">
          <el-upload action :limit="1" :show-file-list="false"
            :before-upload="val => beforeUpload(val, 'uploadVideo', 20)">
            <div style="position: relative;">
              <video v-if="!appear" ishivideo="true" isrotate="true" autoHide="true" controls="controls"
                style="width: 280px;display: block;margin: 10px 0;" @click.stop="()=>{}">
                <source :src="groupForm.materialUrl" type="video/mp4">
              </video>
              <el-button style="float: left;" size="small" type="primary">点击上传</el-button>
            </div>
            <div slot="tip" class="el-upload__tip">
              只能上传mp4文件，且不超过20MB
            </div>
          </el-upload>
        </el-form-item>

        <el-form-item label="其他设置" prop="isSync">
          <el-checkbox v-model="groupForm.isSync">同步到企业库</el-checkbox>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { addVerbal, getGroupList } from '@/api/operate/verbalTrick'
import { nameValidate } from '@/utils/validate'
import {
  uploadInterface,
  uploadVideo
} from '@/api/multimedia/creatingmultimedia.js'

export default {
  data() {
    return {
      appear: true,
      pageLoading: false,
      domain: window.globalConfig.IMAGE_API,
      groupForm: {
        verbalType: 1,
        categoryId: '',
        materialName: '',
        content: '',
        isSync: false
      },
      rules: {
        categoryId: [{ required: true, message: '请选择分组', trigger: 'change' }],
        materialName: [
          { required: true, message: '请输入标题', trigger: 'blur' },
          { required: true, validator: nameValidate(''), trigger: ['change', 'blur'] }
        ],
        verbalType: [{ required: true, message: '请选择话术类型', trigger: 'blur' }],
        content: [{ required: true, message: '请输入话术内容', trigger: 'blur' }]
      },
      personGroupList: [],
      companyGroupList: []
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    submit() {
      this.$refs.groupForm.validate((valid) => {
        if (valid) {
          this.handleAddVerbal()
        } else {
          return false
        }
      })
    },
    handleAddVerbal() {
      this.pageLoading = true
      const params = {
        ...this.groupForm,
        personCategory: this.personGroupList.filter(item => item.id === this.groupForm.categoryId)?.[0]?.name, // 个人分组中文
        isSync: this.groupForm.isSync ? '是' : '否'
      }
      addVerbal(params)
        .then(res => {
          this.pageLoading = false
          if (res.code === 200) {
            this.$message.success(res.msg || '新增成功')
            this.$router.push({
              name: 'VerbalTrick', query: { is_person: this.$route.query.is_person }
            })
          }
        })
        .catch(err => {
          this.pageLoading = false
        })
    },
    goBack() {
      this.$router.push({
        name: 'VerbalTrick', query: { is_person: this.$route.query.is_person }
      })
    },
    init() {
      const params = {
        levelType: 1,
        mediaType: 8
      }
      this.pageLoading = true
      getGroupList(params)
        .then(res => {
          this.pageLoading = false
          if (res.code === 200) {
            this.personGroupList = res.data || []
          }
        })
        .catch(() => {
          this.pageLoading = false
        })
    },
    handleChange() {
      this.groupForm.imgUrl = ''
      this.groupForm.materialUrl = ''
      this.appear = true
    },
    beforeUpload(file, uploadMethod, maxSize = 5) {
      let format = file.type,
        size = file.size / 1024 / 1024
      if (uploadMethod == 'uploadVideo') {
        // 视频
        if (format !== 'video/mp4') return this.$message.error('上传文件只能是 mp4 格式!')
      } else if (uploadMethod == 'uploadInterface') {
        const isJPG = file.type === 'image/jpeg'
        const isPNG = file.type === 'image/png'
        const isGIF = file.type === 'image/gif'
        const isSVG = file.type === 'image/svg+xml'
        const isValidType = isJPG || isPNG || isGIF || isSVG
        if (!isValidType) return this.$message.error('只能上传 jpg/png/gif/svg 文件')
      }
      if (size > maxSize) return this.$message.error(`上传文件大小不能超过 ${maxSize}MB!`)
      let obj = { uploadInterface, uploadVideo }
      this.pageLoading = true
      let formData = new FormData()
      formData.append('file', file)
      this.groupForm.materialUrl = ''
      // uploadInterface(formData)
      obj[uploadMethod](formData)
        .then((res) => {
          if (res.code == 200) {
            this.groupForm.fileSize = res.data.fileSize
            this.groupForm.materialUrl = res.data.url
            this.groupForm.imgUrl = this.domain + res.data.url
            this.groupForm.fileName = res.data.fileName
          }
          this.appear = false
          this.pageLoading = false
        })
        .catch(() => {
          this.groupForm.materialUrl = ''
          this.pageLoading = false
        }).finally(() => this.pageLoading = false)
      return false
    },
  },
}
</script>

<style lang="scss" scoped>
@import "../../../styles/base.scss";

.header-btn {
  @include headerBtn;
}

.from-wrap {
  background: #fff;
  padding: 20px 20% 100px 0;
  margin-top: 16px;
}
</style>
